package com.example.blog.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import com.example.blog.entity.LoginLog;
import com.example.blog.entity.User;
import com.example.blog.mapper.LoginLogMapper;
import com.example.blog.mapper.UserMapper;
import com.example.blog.service.UserService;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private LoginLogMapper loginLogMapper;
    
    @Override
    @Transactional
    public Map<String, Object> register(User user) {
        Map<String, Object> map = new HashMap<>();
        
        // 验证用户名格式（必须是数字）
        if (!user.getLoginName().matches("^[0-9]+$")) {
            map.put("success", false);
            map.put("message", "登录名必须是纯数字");
            return map;
        }
        
        // 验证用户名是否存在
        if (isLoginNameExists(user.getLoginName())) {
            map.put("success", false);
            map.put("message", "该登录名已被使用");
            return map;
        }
        
        // 验证邮箱是否存在
        if (isEmailExists(user.getEmail())) {
            map.put("success", false);
            map.put("message", "该邮箱已被使用");
            return map;
        }
        
        // 加密密码
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        
        // 设置默认状态为 pending
        user.setStatus("pending");
        
        try {
            // 插入用户记录
            int result = userMapper.insert(user);
            if (result > 0) {
                map.put("success", true);
                map.put("message", "注册成功，等待管理员审核");
                map.put("userId", user.getUserId());
            } else {
                map.put("success", false);
                map.put("message", "注册失败，请稍后重试");
            }
        } catch (Exception e) {
            map.put("success", false);
            map.put("message", "系统异常：" + e.getMessage());
        }
        
        return map;
    }

    @Override
    @Transactional
    public Map<String, Object> login(String loginName, String password) {
        Map<String, Object> map = new HashMap<>();
        
        try {
            // 查询用户
            User user = userMapper.selectByLoginName(loginName);
            
            // 记录登录日志
            LoginLog loginLog = new LoginLog();
            loginLog.setUserId(user != null ? user.getUserId() : null);
            loginLog.setLoginDatetime(new Date());
            
            if (user == null) {
                map.put("success", false);
                map.put("message", "用户不存在");
                loginLog.setLoginStatus("failed");
                loginLogMapper.insert(loginLog);
                return map;
            }
            
            // 验证密码
            String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
            if (!user.getPassword().equals(encryptedPassword)) {
                map.put("success", false);
                map.put("message", "密码错误");
                loginLog.setLoginStatus("failed");
                loginLogMapper.insert(loginLog);
                return map;
            }
            
            // 验证用户状态
            if (!"approved".equals(user.getStatus())) {
                map.put("success", false);
                map.put("message", "账号审核中或已禁用");
                loginLog.setLoginStatus("failed");
                loginLogMapper.insert(loginLog);
                return map;
            }
            
            // 登录成功
            loginLog.setLoginStatus("success");
            loginLogMapper.insert(loginLog);
            
            map.put("success", true);
            map.put("message", "登录成功");
            map.put("user", user);
            
            // 不返回密码
            user.setPassword(null);
        } catch (Exception e) {
            map.put("success", false);
            map.put("message", "系统异常：" + e.getMessage());
        }
        
        return map;
    }

    @Override
    public User getUserById(Integer userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        if (user != null) {
            // 不返回密码
            user.setPassword(null);
        }
        return user;
    }

    @Override
    public User getUserByLoginName(String loginName) {
        User user = userMapper.selectByLoginName(loginName);
        if (user != null) {
            // 不返回密码
            user.setPassword(null);
        }
        return user;
    }

    @Override
    public List<User> getAllUsers() {
        List<User> users = userMapper.selectAll();
        
        // 不返回密码
        for (User user : users) {
            user.setPassword(null);
        }
        
        return users;
    }

    @Override
    public List<User> getUsersByStatus(String status) {
        List<User> users = userMapper.selectByStatus(status);
        
        // 不返回密码
        for (User user : users) {
            user.setPassword(null);
        }
        
        return users;
    }

    @Override
    @Transactional
    public Map<String, Object> updateUser(User user) {
        Map<String, Object> map = new HashMap<>();
        
        try {
            // 查询原用户信息
            User originalUser = userMapper.selectByPrimaryKey(user.getUserId());
            if (originalUser == null) {
                map.put("success", false);
                map.put("message", "用户不存在");
                return map;
            }
            
            // 如果修改了邮箱，需要验证新邮箱是否已被使用
            if (!originalUser.getEmail().equals(user.getEmail())) {
                if (isEmailExists(user.getEmail())) {
                    map.put("success", false);
                    map.put("message", "该邮箱已被使用");
                    return map;
                }
            }
            
            // 如果修改了密码，需要加密
            if (user.getPassword() != null && !user.getPassword().isEmpty()) {
                user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
            } else {
                // 如果没有修改密码，使用原密码
                user.setPassword(originalUser.getPassword());
            }
            
            // 确保status字段不为null
            if (user.getStatus() == null) {
                user.setStatus(originalUser.getStatus());
            }
            
            // 设置最后修改时间
            user.setLastModifiedDate(new Date());
            
            // 更新用户信息
            int result = userMapper.updateByPrimaryKey(user);
            if (result > 0) {
                map.put("success", true);
                map.put("message", "更新成功");
            } else {
                map.put("success", false);
                map.put("message", "更新失败");
            }
        } catch (Exception e) {
            map.put("success", false);
            map.put("message", "系统异常：" + e.getMessage());
        }
        
        return map;
    }

    @Override
    @Transactional
    public boolean updateUserStatus(Integer userId, String status) {
        try {
            int result = userMapper.updateStatus(userId, status);
            return result > 0;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean isLoginNameExists(String loginName) {
        return userMapper.checkLoginNameExists(loginName) > 0;
    }

    @Override
    public boolean isEmailExists(String email) {
        return userMapper.checkEmailExists(email) > 0;
    }

    @Override
    @Transactional
    public boolean deleteUser(Integer userId) {
        try {
            int result = userMapper.deleteByPrimaryKey(userId);
            return result > 0;
        } catch (Exception e) {
            return false;
        }
    }
    
    @Override
    @Transactional
    public Map<String, Object> changePassword(Integer userId, String oldPassword, String newPassword) {
        Map<String, Object> map = new HashMap<>();
        
        try {
            // 查询用户信息
            User user = userMapper.selectByPrimaryKey(userId);
            if (user == null) {
                map.put("success", false);
                map.put("message", "用户不存在");
                return map;
            }
            
            // 验证旧密码
            String encryptedOldPassword = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
            if (!user.getPassword().equals(encryptedOldPassword)) {
                map.put("success", false);
                map.put("message", "旧密码不正确");
                return map;
            }
            
            // 加密新密码
            String encryptedNewPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes());
            
            // 更新密码
            user.setPassword(encryptedNewPassword);
            
            // 设置最后修改时间
            user.setLastModifiedDate(new Date());
            
            int result = userMapper.updateByPrimaryKey(user);
            if (result > 0) {
                map.put("success", true);
                map.put("message", "密码修改成功");
            } else {
                map.put("success", false);
                map.put("message", "密码修改失败");
            }
        } catch (Exception e) {
            map.put("success", false);
            map.put("message", "系统异常：" + e.getMessage());
        }
        
        return map;
    }
} 